package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Dispatch;
import com.joint.core.entity.manage.TaskControl;
import com.joint.core.service.DispatchService;
import com.joint.core.service.TaskControlService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;


@ParentPackage("manage")
public class  AjaxTaskcontrolAction extends BaseFlowAction {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private TaskControlService taskControlService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private PowerService powerService;
    @Resource
    private DutyService dutyService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private ReadersService readersService;
    @Resource
    private TaskRecordService taskRecordService;

    /**
     * 任务督办对象(读)
     */
    private TaskControl taskcontrol;

    /**
     * 登录人(读)
     */
    private Users loginUser;
    /**
     * 附件上传Id(读)
     */
    private String fileId;

    /**
     *  任务主题
     */
    private String topic;
    /**
     * 详细要求
     */
    private String demand;
    /**
     * 任务难度系数
     */
    private String degree;

    /**
     * 附件上传Id
     */
    private String fileIds;

    /**
     * 任务责任人id
     */
    private String dutyMansId;

    /**
     * 会办部门id
     */
    private String dealDepartmentId;

    /**
     * 要求完成时间
     */
    private String planFinishDate;

    /**
     * 备注
     */
    private String remark;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "taskcontrol";
    }



    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        if(viewtype !=null && viewtype.equals("2")){
            pager.setOrderBy("modifyDate");
        }
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();

        //params = getSearchFilterParams(_search,params,filters);

        /*内嵌视图这里要加上
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(parentId)){
            manageProInfo = manageProInfoService.get(parentId);
            params.put("manageProInfo",manageProInfo);
        }*/
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
      //  LogUtil.info("viewtype:" + viewtype);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("finish", false);
                pager=taskControlService.findByPagerAndLimit(false, "taskcontrol", pager, params);
            }else if(viewtype.equals("2")){
                //实施中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("finish", false);
                pager=taskControlService.findByPagerAndFinish( "taskcontrol", pager, params);
            }else if(viewtype.equals("3")){
                //已完成
                params.put("finish", true);
                pager=taskControlService.findByPagerAndLimit(true, "taskcontrol", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=taskControlService.findByPagerAndLimit(true, "taskcontrol", pager, params);
        }

        List<TaskControl>  taskControlList;
        if (pager.getTotalCount() > 0){
            taskControlList = (List<TaskControl>) pager.getList();
        }else{
            taskControlList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(TaskControl taskControl: taskControlList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",taskControl.getId());
            String dealDepartment = "";
            for(Department department: taskControl.getDealDepartment()){
                dealDepartment += department.getName() + ",";
            }
            if(dealDepartment.length()>0){
                dealDepartment = dealDepartment.substring(0, dealDepartment.length()-1);
            }
            String dutyMans = "";
            for(Users users:taskControl.getDutyMans()){
                dutyMans += users.getName() + ",";
            }
            if(dutyMans.length() > 0){
                dutyMans =  dutyMans.substring(0, dutyMans.length()-1);
            }
            rMap.put("dealDepartment",dealDepartment);
            rMap.put("dutyMans",dutyMans);
            rMap.put("topic",taskControl.getTopic());
            rMap.put("planFinishDate", DataUtil.DateToString(taskControl.getPlanFinishDate()));
            rMap.put("creater", taskControl.getCreater() != null ? taskControl.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(taskControl.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("state",taskControl.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);


        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            fileId ="";
            taskcontrol = taskControlService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);
            if(taskcontrol.getFile() != null && taskcontrol.getFile().size()>0){
                for(FileManage f:taskcontrol.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "read";
    }


    public String input(){
        Company company = usersService.getCompanyByUser();

        if (StringUtils.isNotEmpty(keyId)){
            fileId ="";
            taskcontrol = taskControlService.get(keyId);
            if(taskcontrol.getFile() != null && taskcontrol.getFile().size()>0){
                for(FileManage f:taskcontrol.getFile()){
                    fileId+=f.getId()+",";
                }
            }

        } else {


        }

        return "input";
    }

    private void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            taskcontrol = taskControlService.get(keyId);
        }else{
            taskcontrol = new TaskControl();
            taskcontrol.setCreater(usersService.getLoginInfo());
        }
        taskcontrol.setTopic(topic);
        taskcontrol.setDemand(demand);
        taskcontrol.setDegree(degree);
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManageService.get(f.trim()));
            }
        }
        taskcontrol.setFile(fileManageList);
        List<Users> usersList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(dutyMansId)){
            String[] idArr = dutyMansId.split(",");
            for(String id:idArr){
                usersList.add(usersService.get(id.trim()));
            }
        }
        taskcontrol.setDutyMans(usersList);
        List<Department> departmentList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(dealDepartmentId)){
            String[] idArr = dealDepartmentId.split(",");
            for(String id:idArr){
                departmentList.add(departmentService.get(id.trim()));
            }
        }
        taskcontrol.setDealDepartment(departmentList);
        taskcontrol.setPlanFinishDate(DataUtil.StringToDate(planFinishDate));
        taskcontrol.setRemark(remark);
        taskcontrol.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                taskControlService.update(taskcontrol);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                taskControlService.save(taskcontrol, "taskcontrol", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }


    // 提交
    public String commit(){
        setData();
        Map<String,Object> params = new HashMap<String,Object>();
        Company com = usersService.getCompanyByUser();
        params.put("company",com);
        params.put("state", BaseEnum.StateEnum.Enable);
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        int count = taskControlService.getList(params).size()+1;
        String taskNoCount = String.valueOf(count);
        String taskNo = "";
        if(taskNoCount.length()==1) {
            taskNo = "000"+taskNoCount;
        }else if(taskNoCount.length()==2){
            taskNo = "00"+taskNoCount;
        }else if(taskNoCount.length()==3){
            taskNo = "0"+taskNoCount;
        }else{
            taskNo = taskNoCount;
        }
        taskcontrol.setTaskNo(taskNo);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        ArrayList<String> list = new ArrayList<String>();
        for (String uid: dutyMansId.split(",")) {
            list.add(uid.trim());
        }
        var2.put("approvers", list);    // 会签人Ids
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                taskControlService.approve(taskcontrol, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = taskControlService.commit(taskcontrol, "taskcontrol", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批1
    public String approve1(){
        taskcontrol = taskControlService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                taskControlService.approve(taskcontrol, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);
            //LogUtil.info("overtask:"+overtask);
            //会签后没有流程将对象状态设为归档
            if(overtask==null){
                TaskControl taskControl = taskControlService.get(keyId);
                taskControl.setProcessState(FlowEnum.ProcessState.Finished);
                taskControlService.update(taskControl);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(taskControl.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }



    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            taskcontrol = taskControlService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("taskcontrol");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
           // System.out.println("comment:"+comment);
             LogUtil.info("numStatus:" + numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            taskControlService.reject(taskcontrol, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            taskcontrol = taskControlService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("taskcontrol");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            taskControlService.deny(taskcontrol, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }


    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }


    public String getDemand() {
        return demand;
    }

    public void setDemand(String demand) {
        this.demand = demand;
    }

    public TaskControl getTaskcontrol() {
        return taskcontrol;
    }

    public void setTaskcontrol(TaskControl taskcontrol) {
        this.taskcontrol = taskcontrol;
    }

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public String getDutyMansId() {
        return dutyMansId;
    }

    public void setDutyMansId(String dutyMansId) {
        this.dutyMansId = dutyMansId;
    }

    public String getDealDepartmentId() {
        return dealDepartmentId;
    }

    public void setDealDepartmentId(String dealDepartmentId) {
        this.dealDepartmentId = dealDepartmentId;
    }

    public String getPlanFinishDate() {
        return planFinishDate;
    }

    public void setPlanFinishDate(String planFinishDate) {
        this.planFinishDate = planFinishDate;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }
}

